# -*- coding: utf-8 -*-
"""
Created on Sun Jan  2 20:30:15 2022

@author: Administrator
"""

import pandas as pd
import numpy as np
import os
from datetime import datetime

today = str(datetime.now().date())

from fastapi import FastAPI
from pydantic import BaseModel
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
from starlette.status import HTTP_201_CREATED
from starlette.status import HTTP_200_OK

import base64
from dateutil.parser import parse
import uvicorn

#import sys
#sys.path.append(r'D:\vue_project\cloud_manage_backend')

from db_model import User_db,Cloud_resource
from db_model import session_cloud_manage

app = FastAPI()

origins = ["*"]
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)



secret_key = 'qjwx123!@#'

# 创建数据模型
class Login(BaseModel):
    username: str
    password: str

@app.post("/login/")
async def handle_login(login:Login):
    abort_if_uesrname_not_exist(login.username)
    try:
        userinfo = session_cloud_manage.query(User_db).filter_by(username = login.username).first()
        if userinfo:
            if login.password == userinfo.password:
                security_str = secret_key + login.password
                token = base64.b64encode(security_str.encode('utf-8'))
                login_res = {
                    'code':200,
                    'username': login.username,
                    'permission': userinfo.permission,
                    'alias': userinfo.alias,
                    'token': token,
                    'msg':'login success',
                }
            else:
                login_res = {
                    'code':500,
                    'username': login.username,
                    'msg':'wrong password',
                }
            return login_res
        else:
            return {"code":404,"message":"未找到用户"}
    except Exception as e:
        session_cloud_manage.rollback()
        return {"code":500,"message":"数据库错误","error":e}
    finally:
        session_cloud_manage.close()

# 查询待办工单
@app.get("/pending/")
async def list_pending(permission: str,status_code=HTTP_200_OK):
    try:
        if permission == 'admin':
            work_order = session_cloud_manage.query(Cloud_resource).filter(Cloud_resource.current_link.in_(['待审批','待验收'])).all()
        else:
            work_order = session_cloud_manage.query(Cloud_resource).filter_by(current_link = '待开通').all()
        if work_order:
            work_orders = [
                {
                'squence' : x.squence,
                'applicant_name' : x.applicant_name,
                'applicant_addres' : x.applicant_addres,
                'unit_contact' : x.unit_contact,
                'telephone' : x.telephone,
                'E_mail' : x.E_mail,
                'business_system_name' : x.business_system_name,
                'interface_tel' : x.interface_tel,
                'cloud_machine_name' : x.cloud_machine_name,
                'operating_system_version' : x.operating_system_version,
                'vCPU_number' : x.vCPU_number,
                'memory_G' : x.memory_G,
                'data_disk' : x.data_disk,
                'network' : x.network,
                'firewall_policy' : x.firewall_policy,
                'remarks1' : x.remarks1,
                'cluster_name' : x.cluster_name,
                'node' : x.node,
                'server_IP' : x.server_IP,
                'port_ID' : x.port_ID,
                'VIP' : x.VIP,
                'remarks2' : x.remarks2,
                'link_10G_quantity_requirement' : x.link_10G_quantity_requirement,
                'special_railway_line' : x.special_railway_line,
                'pm_specifications' : x.pm_specifications,
                'pm_hostname' : x.pm_hostname,
                'pm_operating_system_version' : x.pm_operating_system_version,
                'pm_network' : x.pm_network,
                'pm_firewall_policy' : x.pm_firewall_policy,
                'remarks3' : x.remarks3,
                'current_link' : x.current_link,
                'process' : x.process,
                }
                for x in work_order
            ]
            return JSONResponse(jsonable_encoder(work_orders))
        else:
            return {"code":404,"message":"未找到记录"}
    except Exception as e:
        session_cloud_manage.rollback()
        return {"code":500,"message":"数据库错误","error":e}
    finally:
        session_cloud_manage.close()

# 查询在途工单
@app.get("/initiated/")
async def list_pending(status_code=HTTP_200_OK):
    try:
        work_order = session_cloud_manage.query(Cloud_resource).filter(Cloud_resource.current_link.in_(['待审批','待开通','待验收'])).all()
        if work_order:
            work_orders = [
                {
                'squence' : x.squence,
                'applicant_name' : x.applicant_name,
                'applicant_addres' : x.applicant_addres,
                'unit_contact' : x.unit_contact,
                'telephone' : x.telephone,
                'E_mail' : x.E_mail,
                'business_system_name' : x.business_system_name,
                'interface_tel' : x.interface_tel,
                'cloud_machine_name' : x.cloud_machine_name,
                'operating_system_version' : x.operating_system_version,
                'vCPU_number' : x.vCPU_number,
                'memory_G' : x.memory_G,
                'data_disk' : x.data_disk,
                'network' : x.network,
                'firewall_policy' : x.firewall_policy,
                'remarks1' : x.remarks1,
                'cluster_name' : x.cluster_name,
                'node' : x.node,
                'server_IP' : x.server_IP,
                'port_ID' : x.port_ID,
                'VIP' : x.VIP,
                'remarks2' : x.remarks2,
                'link_10G_quantity_requirement' : x.link_10G_quantity_requirement,
                'special_railway_line' : x.special_railway_line,
                'pm_specifications' : x.pm_specifications,
                'pm_hostname' : x.pm_hostname,
                'pm_operating_system_version' : x.pm_operating_system_version,
                'pm_network' : x.pm_network,
                'pm_firewall_policy' : x.pm_firewall_policy,
                'remarks3' : x.remarks3,
                'current_link' : x.current_link,
                'process' : x.process,
                }
                for x in work_order
            ]
            return JSONResponse(jsonable_encoder(work_orders))
        else:
            return {"code":404,"message":"未找到记录"}
    except Exception as e:
        session_cloud_manage.rollback()
        return {"code":500,"message":"数据库错误","error":e}
    finally:
        session_cloud_manage.close()

# 查询已办工单
@app.get("/done/")
async def list_pending(status_code=HTTP_200_OK):
    try:
        work_order = session_cloud_manage.query(Cloud_resource).filter_by(current_link = '已办结').all()
        if work_order:
            work_orders = [
                {
                'squence' : x.squence,
                'applicant_name' : x.applicant_name,
                'applicant_addres' : x.applicant_addres,
                'unit_contact' : x.unit_contact,
                'telephone' : x.telephone,
                'E_mail' : x.E_mail,
                'business_system_name' : x.business_system_name,
                'interface_tel' : x.interface_tel,
                'cloud_machine_name' : x.cloud_machine_name,
                'operating_system_version' : x.operating_system_version,
                'vCPU_number' : x.vCPU_number,
                'memory_G' : x.memory_G,
                'data_disk' : x.data_disk,
                'network' : x.network,
                'firewall_policy' : x.firewall_policy,
                'remarks1' : x.remarks1,
                'cluster_name' : x.cluster_name,
                'node' : x.node,
                'server_IP' : x.server_IP,
                'port_ID' : x.port_ID,
                'VIP' : x.VIP,
                'remarks2' : x.remarks2,
                'link_10G_quantity_requirement' : x.link_10G_quantity_requirement,
                'special_railway_line' : x.special_railway_line,
                'pm_specifications' : x.pm_specifications,
                'pm_hostname' : x.pm_hostname,
                'pm_operating_system_version' : x.pm_operating_system_version,
                'pm_network' : x.pm_network,
                'pm_firewall_policy' : x.pm_firewall_policy,
                'remarks3' : x.remarks3,
                'current_link' : x.current_link,
                'process' : x.process,
                }
                for x in work_order
            ]
            return JSONResponse(jsonable_encoder(work_orders))
        else:
            return {"code":404,"message":"未找到记录"}
    except Exception as e:
        session_cloud_manage.rollback()
        return {"code":500,"message":"数据库错误","error":e}
    finally:
        session_cloud_manage.close()


# 创建数据模型
class Order(BaseModel):
    applicant_name:str
    applicant_addres:str
    unit_contact:str
    telephone:str
    E_mail:str
    business_system_name:str
    interface_tel:str
    cloud_machine_name:str
    operating_system_version:str
    vCPU_number:int
    memory_G:str
    data_disk:str
    network:str
    firewall_policy:str
    remarks1:str
    cluster_name:str
    node:str
    server_IP:str
    port_ID:str
    VIP:str
    remarks2:str
    link_10G_quantity_requirement:str
    special_railway_line:str
    pm_specifications:str
    pm_hostname:str
    pm_operating_system_version:str
    pm_network:str
    pm_firewall_policy:str
    remarks3:str

# 添加新工单
@app.post("/init/",status_code=HTTP_201_CREATED)
async def init_order(order: Order,name:str):
    today = str(datetime.now().date())
    try:
        order = Cloud_resource(
            applicant_name = order.applicant_name,
            applicant_addres = order.applicant_addres,
            unit_contact = order.unit_contact,
            telephone = order.telephone,
            E_mail = order.E_mail,
            business_system_name = order.business_system_name,
            interface_tel = order.interface_tel,
            cloud_machine_name = order.cloud_machine_name if order.cloud_machine_name else '',
            operating_system_version = order.operating_system_version  if order.operating_system_version else '',
            vCPU_number = order.vCPU_number if order.operating_system_version else 0,
            memory_G = order.memory_G if order.operating_system_version else '',
            data_disk = order.data_disk if order.operating_system_version else '',
            network = order.network if order.operating_system_version else '',
            firewall_policy = order.firewall_policy if order.operating_system_version else '',
            remarks1 = order.remarks1 if order.operating_system_version else '',
            cluster_name = order.cluster_name if order.operating_system_version else '',
            node = order.node,
            server_IP = order.server_IP,
            port_ID = order.port_ID,
            VIP = order.VIP,
            remarks2 = order.remarks2,
            link_10G_quantity_requirement = order.link_10G_quantity_requirement,
            special_railway_line = order.special_railway_line,
            pm_specifications = order.pm_specifications,
            pm_hostname = order.pm_hostname,
            pm_operating_system_version = order.pm_operating_system_version,
            pm_network = order.pm_network,
            pm_firewall_policy = order.pm_firewall_policy,
            remarks3 = order.remarks3,
            current_link = '待审批',
            process = today + '：{}创建申请\n'.format(name),
        )
        session_cloud_manage.add(order)
        session_cloud_manage.commit()
        return {"code":201,"message":"添加成功"}
    except Exception as e:
        session_cloud_manage.rollback()
        return {"code":500,"message":"数据库错误","error":e}
    finally:
        session_cloud_manage.close()

# 审批工单
@app.get("/approval/",status_code=HTTP_200_OK)
async def approval_order(squence:int,process:str,name:str):
    today = str(datetime.now().date())
    try:
        update_order = session_cloud_manage.query(Cloud_resource).filter_by(squence = squence).first()
        if update_order:
            if update_order.current_link == '待审批':
                session_cloud_manage.query(Cloud_resource).filter(Cloud_resource.squence==squence).update({
                    'current_link': '待开通',
                    'process': process + '\n' + today + '：{}审批同意\n'.format(name),
                })
                session_cloud_manage.commit()
                return {"code":200, "message":"审批成功"}
            else:
                pass
        else:
            return {"code":404,"message": "未找到记录"}
    except Exception as e:
        session_cloud_manage.rollback()
        return {"code":500,"message":"数据库错误","error":e}
    finally:
        session_cloud_manage.close()

# 开通工单
@app.get("/open/",status_code=HTTP_200_OK)
async def approval_order(squence:int,process:str,name:str):
    today = str(datetime.now().date())
    try:
        update_order = session_cloud_manage.query(Cloud_resource).filter_by(squence = squence).first()
        if update_order:
            if update_order.current_link == '待开通':
                session_cloud_manage.query(Cloud_resource).filter(Cloud_resource.squence==squence).update({
                    'current_link' : '待验收',
                    'process': process + '\n' + today + '：{}开通竣工\n'.format(name),
                })
                session_cloud_manage.commit()
                return {"code":200, "message": "开通成功"}
            else:
                pass
        else:
            return {"code":404, "message": "未找到记录"}
    except Exception as e:
        session_cloud_manage.rollback()
        return {"code":500,"message":"数据库错误","error":e}
    finally:
        session_cloud_manage.close()

# 验收工单
@app.get("/check/",status_code=HTTP_200_OK)
async def approval_order(squence:int,process:str,name:str):
    today = str(datetime.now().date())
    try:
        update_order = session_cloud_manage.query(Cloud_resource).filter_by(squence = squence).first()
        if update_order:
            if update_order.current_link == '待验收':
                session_cloud_manage.query(Cloud_resource).filter(Cloud_resource.squence==squence).update({
                    'current_link':'已办结',
                    'process': process + '\n' + today + '：{}通过验收\n'.format(name),
                })
                session_cloud_manage.commit()
                return {"code":200, "message": "验收成功"}
            else:
                pass
        else:
            return {"code":404, "message": "未找到记录"}
    except Exception as e:
        session_cloud_manage.rollback()
        return {"code":500,"message":"数据库错误","error":e}
    finally:
        session_cloud_manage.close()


def abort_if_uesrname_not_exist(username):
    uesrname_list = session_cloud_manage.query(User_db).filter_by(username = username).first()
    if not uesrname_list:
        abort(404, message="username: {} not exist".format(username))


if __name__ == '__main__':
    uvicorn.run(app='cloud_manage_backend:app', host="127.0.0.1", port=5000, reload=True)



